//this module offers functions to access messages

#include "message.h"

/* Returns 1 if the messages have the same priority */
int32_t compare_priority(void* arg1, void* arg2){
  message* m1 = (message*)arg1;
  message* m2 = (message*)arg2;
  return m2->priority == m1->priority;
}

/* Returns 1 if the messaes have the same sender */
int32_t compare_from(void* arg1, void* arg2){
  message* m1 = (message*)arg1;
  message* m2 = (message*)arg2;
  return m2->from == m1->from;
}

/* Frees a message */
int32_t free_message(message* m, int32_t owner){
  if(m == NULL)
    return FAILURE;
  if(m->data_flag == STR_DATA){
    if(free(m->data.str_data,owner) == FAILURE)
      return FAILURE;
  }
  return free(m, owner);
}

/* setters */

void message_set_from(message* target, int32_t from){
    target->from = from;
}

void message_set_to(message* target, int32_t to){
    target->to = to;
}

void message_set_data_flag(message* target, int8_t data_flag){
    target->data_flag = data_flag;
}

void message_set_priority(message* target, int32_t priority){
    target->priority = priority;
}

void message_set_int_value(message* target, int32_t value){
    target->data_flag = INT_DATA;
    target->data.int_data = value;
}

/* Returns either SUCCESS, FAILURE or OUT_OF_MEMORY */
int32_t message_set_str_value(message* target, char* value, int32_t owner){
    target->data_flag = STR_DATA;
    int32_t length = strlen(value)+1;
    target->data.str_data = malloc(length*sizeof(char), owner);
    if(target->data.str_data == NULL)
      return OUT_OF_MEMORY;
    strncpy(target->data.str_data, value, length);
    return SUCCESS;
}

void message_set_pinfo_values(message* target, uint32_t priority, int32_t program_id, int32_t parent, int32_t status){
  target->data.pinfo_data.priority = priority;
  target->data.pinfo_data.program_id = program_id;
  target->data.pinfo_data.parent = parent;
  target->data.pinfo_data.status = status;
}
